<template>
    <div>
        <!-- 租客退租 -->
        <Modal
            v-model="isModalVisible"
            :closable="false"
            :mask-closable="false"
            :loading="true"
            title="租客退租"
            class-name="vertical-center-modal"
            width="640">

            <Form ref="checkInForm" :label-width="120"
            style="height: 100%;">

                <Row class="renter-list-cells margin-bot-16">
                    <Col span="4" class="info-title">租客姓名：</Col>
                    <Col span="9">{{renter.name || '-' }}</Col>
                </Row>
                <Row class="renter-list-cells margin-bot-16">
                    <Col span="4" class="info-title">手机号码：</Col>
                    <Col span="7">{{renter.phone || '-'}}</Col>
                </Row>

                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间地址：</Col>
                    <Col span="9">{{leaseInfo.home_address}}</Col>
                </Row>
                <Row class="renter-list-info margin-bot-5" type="flex" align="middle">
                    <Col span="4" class="info-title">房间名称：</Col>
                    <Col span="7">{{leaseInfo.room_name}}</Col>
                </Row>

                <div class="split-line" v-if="leaseInfo.co_tenants.length"></div>
                <Row class="renter-list-cells margin-bot-5" v-for="(item,index) in leaseInfo.co_tenants" :key="index">
                    <Col span="4" style="text-align:right">同租人：</Col>
                    <Col span="3">{{item.name }}</Col>
                    <Col span="3" style="text-align:right">电话：</Col>
                    <Col span="3">{{item.phone}}</Col>
                    <Col span="4" style="text-align:right">关系：</Col>
                    <Col span="7">{{item.co_tenant_lease && item.co_tenant_lease.relationship}}</Col>
                </Row>


                <div class="split-line"></div>

                <FormItem label="租约有效期：" class="margin-bot-5">
                    <span>{{new Date(leaseInfo.lease_range[0]).Format('yyyy-MM-dd HH:mm')}} - </span>
                    <span>{{new Date(leaseInfo.lease_range[1]).Format('yyyy-MM-dd HH:mm')}}</span>
                </FormItem>

                <div class="split-line"></div>

                <!--  暂时隐藏门禁
                <Row class="renter-list-info" type="flex" align="middle" v-if="hasAccessControl">
                    <Col span="4" style="text-align:right">门禁：</Col>
                    <Col span="6">暂无</Col>
                    <Col span="14">
                        <Checkbox style="margin-left:10px" v-model="delDoor"> 回收门禁卡权限</Checkbox>
                    </Col>
                </Row> -->

                <Row class="renter-list-info" type="flex" align="middle">
                    <Col span="4" style="text-align:right">开门授权：</Col>

                    <Col span="20">
                        <Checkbox v-model="isDeletePassword" style="padding-left: 15px;" :disabled="isNoGatewayLock">退租同时删除租客关联的所有密码</Checkbox>
                    </Col>
                </Row>

                <div class="split-line" v-if="hasLock"></div>

                <FormItem v-if="overdraft && hasElemeter" label="当前电表读数：" class="margin-bot-5">
                    {{roomInfo.electric_read || 0}} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd')}}）
                </FormItem>
                <FormItem v-if="!overdraft && hasElemeter" label="当前剩余电量：" class="margin-bot-5">
                    {{ leftElectric }} KWH （更新于 {{new Date(roomInfo.updated_at || Date.now()).Format('yyyy/MM/dd')}}）
                </FormItem>

                <!-- <FormItem label="备注" prop="mark">
                    <Input type="textarea" v-model="checkInFormItem.note" placeholder="请填入备注信息"/>
                </FormItem> -->
            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="cancelOut('checkInForm')">取消</Button>
                <Button :loading="!leaseInfo.id || isLoading" type="primary" size="large" @click="handleClick('checkInForm')">退租</Button>
            </div>
        </Modal>

        <Modal v-model="isShowPasswordModal && !!this.passwordDetail.length" title="删除门锁密码" width="740" :closable="false" :mask-closable="false">
            <Row v-for="(item, index) in this.passwordDetail" :key="index" >
                <p style="text-align: center; font-size: 20px;">{{item.name === 'room' ? '房间' : '公区'}}门锁密码删除指令{{item.result === 'ok' ? '成功,请去门锁授权列表里面检查相应的密码状态' : '失败,请去门锁授权列表里面对相应的密码进行操作'}}</p>

                <br>

                <p v-if="item.activation_password_ids" v-for="(id, index) in item.activation_password_ids" :key="index">离线密码{{id}}当天下发，为保障安全，请于次日操作</p>

                <Row v-if="item.unable_batch_operate_pwds">
                    <p>{{item.name === 'room' ? '房间' : '公区'}}门锁版本过低，无法批量删除密码</p>
                    <p>为保障安全，请在{{item.name === 'room' ? '房间' : '公区'}}门锁授权列表中对下列密码进行操作</p>
                    <br/>

                   <Table :columns="columns" :data="item.unable_batch_operate_pwds"></Table>
                </Row>
                <br/>
            </Row>

            <div slot="footer">
                <Button type="ghost" size="large" @click="ok">确定</Button>
            </div>
        </Modal>

        <operateResultModal v-if="isResultModalVisible" @confirm="closeOutModal" :operateResult="operateResult" :operateResultMulti="operateResultMulti"></operateResultModal>
    </div>


</template>

<script>
// import validate from '@/libs/validate';
import { mapState } from 'vuex'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import operateResultModal from './operateResultModal'

export default {
  props: {
    renterId: {
      // 租客Id,必须
      required: false
    },
    lease: {
      // 租赁信息
      type: Object,
      required: false
    },
    room: {
      // 房间信息
      type: Object,
      required: false
    },
    faceAccess: Boolean
  },
  components: {
    operateResultModal
  },
  data () {
    let now = Date.now()
    return {
      columns: [
        {
          title: '授权编号',
          align: 'center',
          key: 'paas_password_id'
        },
        {
          title: '状态',
          align: 'center',
          key: 'pwd_state',
          render: (h, params) => {
            const {
              row: { pwd_state }
            } = params
            return h('span', util.getPasswordStatus(pwd_state))
          }
        },
        {
          title: '被授权人信息',
          align: 'center',
          key: 'name',
          render: (h, params) => {
            const {
              row: { name, send_to }
            } = params
            return h('span', name + ' ' + send_to)
          }
        },
        {
          title: '关联租客',
          align: 'center',
          key: 'tenant_name'
        }
      ],
      isShowPasswordModal: false, // 是否展示密码弹窗
      passwordDetail: [],
      isDeletePassword: true, // 是否删除相关密码
      renter: {},
      roomInfo: {}, // 具体房间信息
      parentRoomInfo: {},
      delDoor: false,
      leaseId: null,
      passwords: '',
      leaseInfo: {
        lease_range: [now, now],
        co_tenants: []
      },
      options3: {
        disabledDate: date => {
          return date && date.valueOf() < new Date(this.leaseInfo.lease_range[1]).valueOf()
        }
      },
      hasFaceDevice: false,
      isModalVisible: true,
      isResultModalVisible: false,
      operateResult: [],
      operateResultMulti: null,

      isLoading: false
    }
  },
  created () {
    let renterId
    if (this.room) {
      renterId = this.room.lease.tenant && this.room.lease.tenant.id
      this.leaseId = this.room.lease.id
    } else {
      renterId = this.renterId
      this.leaseId = this.lease.id
    }
    this.getRenterInfo(renterId)
  },
  computed: {
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    }),

    // 传入需要删除门禁权限 或 通过租约判断
    hasFaceDeviceAndPermission () {
      return this.faceAccess || (this.hasFaceAccessPermission && this.hasFaceDevice)
    },
    overdraft () {
      // 计算房间是否是后付费
      return this.roomInfo.pay_type === 2
    },
    leftElectric () {
      if (!this.roomInfo.electric_read) {
        return 0
      }
      return util.getLeftElectric(this.roomInfo)
    },

    /**
        * 是否是指纹锁
        */
    isFingerLock () {
      if (this.roomInfo && this.roomInfo.devices && this.roomInfo.devices.some((device) => (device.device_ability.includes('LOCK') && device.model && device.model === 'lk-19'))) {
        return true
      } else {
        return false
      }
    },

    isNoGatewayLock () {
      if (this.roomInfo && this.roomInfo.devices && this.roomInfo.devices.some((item) => (item.device_type === DeviceTypeEnum.LOCK && item.parent === 'GOD'))) {
        this.isDeletePassword = false
        return true
      } else {
        return false
      }
    },

    hasLock () {
      let selfHas // 本房间是否有设备
      let parentHas // 公区房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.LOCK
        })
      }

      if (this.parentRoomInfo.devices) {
        parentHas = this.parentRoomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.LOCK
        })
      }
      return selfHas || parentHas // 房间或者公区有门锁，就显示门锁密码相关
    },
    hasElemeter () {
      let selfHas // 本房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.ELEMETER
        })
      }

      return selfHas // 房间有电表才显示电表相关
    },
    hasAccessControl () {
      return false
    }
  },
  methods: {
    ok () {
      this.isShowPasswordModal = false
      this.isResultModalVisible = true
    },

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    getRenterInfo (renterId) {
      http.request(this, api.tenant_info, [renterId], null, res => {
        if (res) {
          // 获取到租客信息
          this.renter = res
          if (this.room) {
            this.getRoomInfo(this.room.id)
            res.lease_list.forEach(item => {
              // 筛选租赁信息
              if (item.room_id === this.room.id) {
                this.leaseInfo = item
                this.hasFaceDevice = item.face_auth_devices && item.face_auth_devices.length > 0
              }
            })
          } else {
            this.leaseInfo = this.lease
            this.getRoomInfo(this.lease.room_id)
          }
        }
      })
    },

    actionDelDoor () {
      return new Promise((resolve, reject) => {
        if (!this.delDoor || !this.hasAccessControl) {
          return resolve()
        }
        resolve()
      })
    },

    actionDelPassword () {
      http.request(this, api.lease_password_delete, [this.leaseInfo.id], null, (res, error) => {
        if (error) {
          return
        }

        this.passwordDetail = []
        Object.keys(res).forEach((key) => {
          this.constructData(key, res[key])
        })

        this.isModalVisible = false
        this.isShowPasswordModal = true

        if (!this.passwordDetail.length) { // 如果房间和公区都没有门锁直接删除
          this.ok()
        }
      })
    },

    /**
        * 构造门锁返回的密码列表
        */
    constructData (key, password) {
      this.passwordDetail.push({name: key, ...password})
    },

    sendOutRequest () {
      // 租客退租
      let lease_id = this.leaseInfo.id
      this.operateResult.push({
        params: [api.tenant_leases_del, [lease_id], null],
        title: '删除租赁记录'
      })

      this.hasFaceDeviceAndPermission && this.operateResult.push({
        params: [api.detory_face_access_auth, [lease_id], null],
        title: '删除门禁授权'
      })
    },

    closeOutModal () {
      this.$emit('outSuccess')
      this.$store.commit('refresh_renter', Math.random())
    },

    handleClick () {
      // 发送删除密码、门禁请求
      if (this.isDeletePassword) {
        this.actionDelPassword() // 删除密码
      }

      if (this.isFingerLock) { // 如果是指纹锁
        http.request(this, api.leases_grant_record, [this.leaseInfo.id], null, (res, error) => {
          if (error || !res) {
            return
          }

          let pos = false
          res.forEach((room) => {
            if (room.passwords && room.passwords.some((password) => (password.type === 2))) {
              pos = true
            }
          })

          if (pos) { // 如果存在指纹密码调用删除
            this.deleteFingerPassword()
          }
        })
      }

      this.sendOutRequest() // 发送退租请求(需要在删除密码之后)
      // 显示操作结果

      if (!this.isDeletePassword) {
        this.isResultModalVisible = true
      }
    },

    // 删除指纹授权记录
    deleteFingerPassword () {
      const obj = {
        params: [api.finger_password_del_mutil, [this.leaseId], null],
        specialTitle: '删除开门指纹'
      }
      this.operateResultMulti = obj
    },

    cancelOut () {
      this.$emit('cancelOut')
    },
    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
          this.getParentRoomInfo(this.roomInfo.parent_id)
        }
      })
    },
    getParentRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.parentRoomInfo = res
        }
      })
    }
  }
}
</script>

<style lang="less">
.margin-bot-16 {
    margin-bottom: 16px;
}
.margin-bot-5 {
    margin-bottom: 5px;
}
</style>
<style lang="less" scoped>
    .info-title {
        text-align:right;
        width:120px;
        padding-right:22px;
    }
</style>